import axios from 'axios'
import toast from 'react-hot-toast';

const axiosInstance = axios.create({
    baseURL: '/api/v1',
    timeout: 1000,
});


type RequestConfig = {
    data?: any,
    success?: (res: any) => void,
    error?: (err: any) => void,
    showError: boolean,
    showSuccess: boolean,
}

const defaultConfig: RequestConfig = {
    showError: true,
    showSuccess: false
}

const successResHandler = (config: RequestConfig, res: any,) => {
    // 网络正常
    if (res.status === 200) {
        // √ 数据正常 
        if (res.data.code === 1) {
            config.success && config.success(res.data.data)
            if (config.showSuccess) toast.success(res.data.message || '请求成功')
        // 数据异常
        }else{
            config.error && config.error(res.data)
            if (config.showError) toast.error(res.data.message || '请求错误')
        }
    // 网络异常
    } else {
        config.error && config.error(res.data)
        if (config.showError) toast.error(res.data.message || '网络错误')
    }
}

const errorResHandler = (config: RequestConfig, err: any) => {
    config.error && config.error(err)
    if (config.showError) toast.error('未知错误')
}


const get = (url: string, config: RequestConfig) => {
    const _config = { ...defaultConfig, ...config }
    return axiosInstance.get(url, {
        params: config.data || {}
    }).then(successResHandler.bind(null, _config)).catch(errorResHandler.bind(null, _config))
}

const post = (url: string, config?: any) => {
    const _config = { ...defaultConfig, ...config }
    return axiosInstance.post(url, _config.data).then(successResHandler.bind(null, _config)).catch(errorResHandler.bind(null, _config))
}

export default {
    get,
    post
}

